<template>
  <div class="social-media-reverse-check-container">
    <!-- 顶部栏与侧边栏将由MainHeader和SideMenu组件提供 -->
    <MainHeader />
    
    <div class="main-container">
      <!-- 左侧导航 -->
      <SideMenu />
      
      <!-- 主内容区域 -->
      <div class="content-container">
        <div class="search-content">
          <div class="page-header">
            <div class="title">{{ t('social.media.title') }}</div>
            <div class="description">
              {{ t('social.media.description') }}
            </div>
          </div>
          
          <div class="search-actions">
            <el-button :type="searchType === 'linkedin' ? 'primary' : 'default'" class="action-button" @click="searchType = 'linkedin'">
              <el-icon><Link /></el-icon>
              {{ t('social.media.linkedin.data') }}
            </el-button>
            
            <el-button :type="searchType === 'twitter' ? 'primary' : 'default'" class="action-button" @click="searchType = 'twitter'">
              <el-icon><ChatDotRound /></el-icon>
              {{ t('social.media.twitter.data') }}
            </el-button>
          </div>
          
          <div class="search-box">
            <el-input
              :placeholder="searchType === 'linkedin' ? t('social.media.linkedin.placeholder') : t('social.media.twitter.placeholder')"
              v-model="searchKeyword"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-button type="primary" class="search-button" @click="handleSearch" :loading="loading">{{ t('social.media.search.button') }}</el-button>
            <el-button type="success" class="action-button batch-search-btn" @click="showBatchDialog = true">
              <el-icon :size="18"><Upload /></el-icon>
              {{ getCurrentLanguage() === 'zh' ? '批量反查' : 'Batch Reverse' }}
            </el-button>
          </div>
          
          <!-- API错误信息 -->
          <div v-if="apiError" class="api-error-alert">
            <el-alert
              type="error"
              :description="`请求失败: ${apiError}。`"
              show-icon
              closable
            />
          </div>
          
          <!-- 搜索结果区域 -->
          <div class="search-results" v-if="searchResults.length">
            <div class="results-header">
              <h3>{{ t('social.media.results') }} ({{ searchResults.length }}条)</h3>
              <el-button size="small" @click="clearResults">{{ t('social.media.return') }}</el-button>
            </div>
            
            <div class="result-cards">
              <div v-for="(result, index) in searchResults" :key="index" class="result-card">
                <div class="result-header">
                  <h4>{{ result.name || result.Full_name || result.screen_name || t('social.media.unknown') }}</h4>
                  <div class="result-source">{{ getSourceName(result.source) }}</div>
                </div>
                
                <div class="result-content">
                  <!-- 展示所有非空字段 -->
                  <template v-for="(value, key) in getFilteredFields(result)" :key="key">
                    <div class="info-row">
                      <span class="info-label">{{ getFieldLabel(key) }}:</span>
                      <span class="info-value" :class="{ 
                        highlight: isUrlField(key) || isEmailField(key) || isPhoneField(key)
                      }">
                        {{ value }}
                      </span>
                      <el-button v-if="isUrlField(key)" 
                               size="small" 
                               @click="openUrl(value)" 
                               class="copy-btn">{{ t('social.media.visit') }}</el-button>
                      <el-button v-if="isEmailField(key) || isPhoneField(key)" 
                               size="small" 
                               @click="copyToClipboard(value)" 
                               class="copy-btn">{{ t('social.media.copy') }}</el-button>
                    </div>
                  </template>
                </div>
              </div>
            </div>
            
            <!-- 加载更多按钮 -->
            <div class="load-more" v-if="searchResults.length < totalResults">
              <el-button type="primary" plain @click="loadMore" :loading="loading">{{ t('social.media.load.more') }}</el-button>
            </div>
          </div>
          
          <!-- 无搜索结果 -->
          <div class="no-results" v-if="searched && !searchResults.length && !apiError">
            <el-empty :description="t('social.media.no.results')"></el-empty>
          </div>
          
          <!-- 加载状态 -->
          <div class="loading-container" v-if="loading">
            <el-skeleton :rows="5" animated />
          </div>
          
          <!-- 功能介绍卡片，仅在没有搜索结果且未搜索时显示 -->
          <div class="feature-cards" v-if="!searchResults.length && !searched">
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="blue-icon"><Share /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('social.media.feature.linkedin') }}</div>
                <div class="card-desc">{{ t('social.media.feature.linkedin.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="green-icon"><UserFilled /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('social.media.feature.twitter') }}</div>
                <div class="card-desc">{{ t('social.media.feature.twitter.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="purple-icon"><Histogram /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('social.media.feature.multi.dimension') }}</div>
                <div class="card-desc">{{ t('social.media.feature.multi.dimension.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="40" class="orange-icon"><Star /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('social.media.feature.complete.info') }}</div>
                <div class="card-desc">{{ t('social.media.feature.complete.info.desc') }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 批量反查对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      :title="getCurrentLanguage() === 'zh' ? '批量社媒反查' : 'Batch Social Media Reverse Check'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-content">
        
        <el-alert
          :title="getCurrentLanguage() === 'zh' ? '使用说明' : 'Instructions'"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <div v-if="getCurrentLanguage() === 'zh'">
              <p>1. <strong>LinkedIn查询</strong>：请上传包含"领英链接"和"姓名"列的Excel文件</p>
              <p>2. <strong>Twitter查询</strong>：请上传包含"姓名"和"用户名"列的Excel文件</p>
              <p>3. 系统将根据表头组合自动识别查询类型</p>
              <p>4. 支持的列名：LinkedInUrl/领英链接、Name/姓名、Username/用户名/ScreenName</p>
              <p>5. 搜索结果将自动下载为Excel文件，只有包含数据的数据源才会生成工作表</p>
            </div>
            <div v-else>
              <p>1. <strong>LinkedIn Query</strong>: Upload Excel with "LinkedInUrl" and "Name" columns</p>
              <p>2. <strong>Twitter Query</strong>: Upload Excel with "Name" and "Username" columns</p>
              <p>3. The system will automatically identify the query type based on header combinations</p>
              <p>4. Supported column names: LinkedInUrl, Name, Username/ScreenName</p>
              <p>5. Results will be downloaded as Excel, only data sources with results will generate worksheets</p>
            </div>
          </template>
        </el-alert>
        
        <!-- 文件上传 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
          :file-list="fileList"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            {{ getCurrentLanguage() === 'zh' ? '将Excel文件拖到此处，或' : 'Drop Excel file here or' }}
            <em>{{ getCurrentLanguage() === 'zh' ? '点击上传' : 'click to upload' }}</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              {{ getCurrentLanguage() === 'zh' ? '仅支持 .xlsx 和 .xls 格式的文件' : 'Only .xlsx and .xls files are supported' }}
            </div>
          </template>
        </el-upload>
        
        <!-- 进度条 -->
        <div v-if="batchUploading" style="margin-top: 20px;">
          <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
          <div style="text-align: center; margin-top: 10px; color: #606266;">
            {{ uploadStatusText }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <!-- 下载模板按钮 -->
          <el-button type="warning" plain @click="downloadTemplate('linkedin')">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载LinkedIn模板' : 'LinkedIn Template' }}
          </el-button>
          <el-button type="warning" plain @click="downloadTemplate('twitter')" style="margin-left: 10px;">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载Twitter模板' : 'Twitter Template' }}
          </el-button>

          <el-button @click="cancelBatchUpload">
            {{ getCurrentLanguage() === 'zh' ? '取消' : 'Cancel' }}
          </el-button>
          <el-button
            type="primary"
            @click="submitBatchReverse"
            :loading="batchUploading"
            :disabled="!selectedFile"
          >
            {{ getCurrentLanguage() === 'zh' ? '开始反查' : 'Start Reverse' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Search, Link, Share, UserFilled, Histogram, Star, ChatDotRound, Upload, UploadFilled, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { useRouter } from 'vue-router'
import { t } from '@/utils/i18n'
import {getCurrentLanguage} from "../utils/i18n";

// 定义响应式数据
const searchType = ref('linkedin') // linkedin 或 twitter
const searchKeyword = ref('')
const searchResults = ref([])
const loading = ref(false)
const searched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalResults = ref(0)
const apiError = ref(null)
const router = useRouter()

// 批量反查相关数据
const showBatchDialog = ref(false)
const selectedFile = ref(null)
const fileList = ref([])
const uploadRef = ref(null)
const batchUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadStatusText = ref('')

// 实际搜索函数
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning(searchType.value === 'linkedin' ? '请输入领英关键词' : '请输入推特关键词')
    } else {
      ElMessage.warning(searchType.value === 'linkedin' ? 'please input linkedin keyword' : 'please input twitter keyword')
    }
    return
  }
  
  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录后再进行查询')
    } else {
      ElMessage.warning('You have not logged in yet, please log in first before searching')
    }
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', '/social-media-reverse-check')
    // 跳转到登录页
    router.push('/login')
    return
  }
  
  // 统计真实搜索次数
  let count = parseInt(localStorage.getItem('searchCount_socialReverse') || '0')
  localStorage.setItem('searchCount_socialReverse', count + 1)
  
  loading.value = true
  searched.value = true
  currentPage.value = 1
  apiError.value = null
  searchResults.value = []
  
  try {
    const response = await axios.get('/api/social-media-lookup', {
      params: {
        keyword: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      },
      // 添加超时设置
      timeout: 60000 // 增加超时时间到60秒，因为现在需要查询多个分片
    });
    
    if (response.data && typeof response.data === 'object') {
      searchResults.value = response.data.results || [];
      totalResults.value = response.data.total || 0;
      
      // 检查是否返回了错误信息
      if (response.data.error) {
        apiError.value = response.data.error;
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`搜索出现错误: ${response.data.error}`);
        } else {
          ElMessage.error(`Search failed`);
        }
      } else if (searchResults.value.length === 0) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.info('未找到匹配的结果');
        } else {
          ElMessage.info('No matching results found');
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.success(`找到 ${totalResults.value} 条匹配记录`);
        } else{
          ElMessage.success(`Found ${totalResults.value} matching records`);
        }
      }
    } else {
      apiError.value = '服务器返回的数据格式不正确';
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器返回的数据格式不正确');
      } else {
        ElMessage.error('Server returned data in an incorrect format');
      }
      searchResults.value = [];
      totalResults.value = 0;
    }
  } catch (error) {

    // 详细的错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status;
      apiError.value = `服务器返回错误(${status}): ${error.response.data?.message || error.message || '未知错误'}`;
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      apiError.value = '服务器未响应，请检查后端服务是否正常运行';
    } else {
      // 请求设置触发的错误
      apiError.value = `请求错误: ${error.message}`;
    }

    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`搜索失败: ${apiError.value}`);
    } else {
      ElMessage.error(`Search failed`);
    }
    searchResults.value = [];
    totalResults.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载更多结果
const loadMore = async () => {
  if (searchResults.value.length >= totalResults.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('已加载全部数据');
    } else {
      ElMessage.info('All data has been loaded');
    }
    return;
  }

  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您的登录已过期，请重新登录')
    } else {
      ElMessage.warning('Your login has expired, please log in again')
    }
    router.push('/login')
    return
  }

  loading.value = true;
  currentPage.value += 1;
  
  try {
    const response = await axios.get('/api/social-media-lookup', {
      params: {
        keyword: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      },
      timeout: 60000 // 增加超时时间
    });
    
    const newResults = response.data.results || [];
    searchResults.value = [...searchResults.value, ...newResults];
    
    if (newResults.length === 0) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.info('没有更多数据了');
      } else {
        ElMessage.info('No more data');
      }
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`加载更多失败: ${error.message || '服务器连接失败'}`);
    } else {
      ElMessage.error(`Failed to load more`);
    }
    currentPage.value -= 1;
  } finally {
    loading.value = false;
  }
};

// 清除搜索结果
const clearResults = () => {
  searchResults.value = [];
  searched.value = false;
  currentPage.value = 1;
  totalResults.value = 0;
  apiError.value = null;
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('已复制到剪贴板');
      } else {
        ElMessage.success('Copied to clipboard');
      }
    })
    .catch(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('复制失败，请手动复制');
      } else {
        ElMessage.error('Copy failed, please manually copy');
      }
    });
};

// 打开URL
const openUrl = (url) => {
  let fullUrl = url;
  
  // 如果URL不包含协议，添加https://
  if (!/^https?:\/\//i.test(url)) {
    fullUrl = 'https://' + url;
  }
  
  window.open(fullUrl, '_blank');
};

// 判断是否为URL字段
const isUrlField = (key) => {
  const urlFields = [
    'LinkedIn_Url', 'linkedin_url', 
    'Facebook_Url', 'facebook_url', 
    'Twitter_Url', 'twitter_url', 
    'Github_Url', 'github_url', 
    'Company_Website', 'company_website', 
    'Company_Linkedin_Url', 'company_linkedin_url', 
    'Company_Facebook_Url', 'company_facebook_url', 
    'Company_Twitter_Url', 'company_twitter_url', 
    'url', 'website'
  ];
  return urlFields.includes(key.toLowerCase()) || urlFields.includes(key);
};

// 判断是否为邮箱字段
const isEmailField = (key) => {
  const emailFields = ['email', 'emails', 'Email', 'Emails'];
  return emailFields.includes(key.toLowerCase()) || emailFields.includes(key);
};

// 判断是否为电话字段
const isPhoneField = (key) => {
  const phoneFields = ['phone', 'phone_numbers', 'Phone_numbers', 'Mobile', 'mobile', 'telephone'];
  return phoneFields.includes(key.toLowerCase()) || phoneFields.includes(key);
};

// 获取数据源名称
const getSourceName = (source) => {
  const sourceMap = {
    'linkedin_data': t('social.media.source.linkedin'),
    'twitter_data': t('social.media.source.twitter'),
    'twitter_users': t('social.media.source.twitter'),
    'ly_user': t('social.media.source.linkedin')
  };
  return sourceMap[source] || t('social.media.source.unknown');
};

// 过滤掉空字段和source字段
const getFilteredFields = (result) => {
  const filteredObj = {};
  Object.entries(result).forEach(([key, value]) => {
    if (value !== null && value !== undefined && value !== '' && key !== 'source') {
      filteredObj[key] = value;
    }
  });
  return filteredObj;
};

// 获取字段名称的标签，根据当前语言环境显示中文或英文
const getFieldLabel = (key) => {
  // 检测当前语言
  const currentLang = localStorage.getItem('APP_LANGUAGE') || 'zh';
  const isEnglish = currentLang === 'en';

  // 统一转换为小写进行匹配
  const keyLower = key.toLowerCase();
  
  // 字段名映射表，同时包含中英文
  const fieldLabels = {
    // LinkedIn数据 (兼容不同的字段命名风格)
    'id': { 'zh': '主键ID', 'en': 'ID' },
    'full_name': { 'zh': '全名', 'en': 'Full Name' },
    'industry': { 'zh': '行业', 'en': 'Industry' },
    'job_title': { 'zh': '职位头衔', 'en': 'Job Title' },
    'sub_role': { 'zh': '子角色', 'en': 'Sub Role' },
    'industry_2': { 'zh': '第二行业', 'en': 'Secondary Industry' },
    'emails': { 'zh': '邮箱', 'en': 'Emails' },
    'mobile': { 'zh': '手机号码', 'en': 'Mobile Phone' },
    'phone_numbers': { 'zh': '电话号码', 'en': 'Phone Numbers' },
    'company_name': { 'zh': '公司名称', 'en': 'Company Name' },
    'company_industry': { 'zh': '公司行业', 'en': 'Company Industry' },
    'company_website': { 'zh': '公司网站', 'en': 'Company Website' },
    'company_size': { 'zh': '公司规模', 'en': 'Company Size' },
    'company_founded': { 'zh': '公司成立年份', 'en': 'Company Founded Year' },
    'location': { 'zh': '所在地', 'en': 'Location' },
    'locality': { 'zh': '地区', 'en': 'Locality' },
    'metro': { 'zh': '都会区', 'en': 'Metro' },
    'region': { 'zh': '区域', 'en': 'Region' },
    'skills': { 'zh': '技能', 'en': 'Skills' },
    'first_name': { 'zh': '名字', 'en': 'First Name' },
    'middle_initial': { 'zh': '中间名首字母', 'en': 'Middle Initial' },
    'middle_name': { 'zh': '中间名', 'en': 'Middle Name' },
    'last_name': { 'zh': '姓氏', 'en': 'Last Name' },
    'birth_year': { 'zh': '出生年份', 'en': 'Birth Year' },
    'birth_date': { 'zh': '出生日期', 'en': 'Birth Date' },
    'gender': { 'zh': '性别', 'en': 'Gender' },
    'linkedin_url': { 'zh': '领英网址', 'en': 'LinkedIn URL' },
    'linkedin_username': { 'zh': '领英用户名', 'en': 'LinkedIn Username' },
    'facebook_url': { 'zh': '脸书网址', 'en': 'Facebook URL' },
    'facebook_username': { 'zh': '脸书用户名', 'en': 'Facebook Username' },
    'twitter_url': { 'zh': '推特网址', 'en': 'Twitter URL' },
    'twitter_username': { 'zh': '推特用户名', 'en': 'Twitter Username' },
    'github_url': { 'zh': 'GitHub网址', 'en': 'GitHub URL' },
    'github_username': { 'zh': 'GitHub用户名', 'en': 'GitHub Username' },
    'company_linkedin_url': { 'zh': '公司领英网址', 'en': 'Company LinkedIn URL' },
    'company_facebook_url': { 'zh': '公司脸书网址', 'en': 'Company Facebook URL' },
    'company_twitter_url': { 'zh': '公司推特网址', 'en': 'Company Twitter URL' },
    'company_location_name': { 'zh': '公司所在地名称', 'en': 'Company Location Name' },
    'company_location_locality': { 'zh': '公司所在地地区', 'en': 'Company Location Locality' },
    'company_location_metro': { 'zh': '公司所在地都会区', 'en': 'Company Location Metro' },
    'company_location_region': { 'zh': '公司所在地区域', 'en': 'Company Location Region' },
    'company_location_geo': { 'zh': '公司所在地地理坐标', 'en': 'Company Location Coordinates' },
    'company_location_street_address': { 'zh': '公司所在地街道地址', 'en': 'Company Street Address' },
    'company_location_address_line_2': { 'zh': '公司所在地地址第二行', 'en': 'Company Address Line 2' },
    'company_location_postal_code': { 'zh': '公司所在地邮政编码', 'en': 'Company Postal Code' },
    'company_location_country': { 'zh': '公司所在地国家', 'en': 'Company Country' },
    'company_location_continent': { 'zh': '公司所在地大洲', 'en': 'Company Continent' },
    'last_updated': { 'zh': '最后更新时间', 'en': 'Last Updated' },
    'start_date': { 'zh': '开始日期', 'en': 'Start Date' },
    'job_summary': { 'zh': '工作摘要', 'en': 'Job Summary' },
    'location_country': { 'zh': '所在地国家', 'en': 'Location Country' },
    'location_continent': { 'zh': '所在地大洲', 'en': 'Location Continent' },
    'street_address': { 'zh': '街道地址', 'en': 'Street Address' },
    'address_line_2': { 'zh': '地址第二行', 'en': 'Address Line 2' },
    'postal_code': { 'zh': '邮政编码', 'en': 'Postal Code' },
    'location_geo': { 'zh': '所在地地理坐标', 'en': 'Location Coordinates' },
    'last_updated_1': { 'zh': '最后更新时间（重复列）', 'en': 'Last Updated (Duplicate)' },
    'linkedin_connections': { 'zh': '领英联系人数量', 'en': 'LinkedIn Connections' },
    'inferred_salary': { 'zh': '推断的薪资', 'en': 'Inferred Salary' },
    'years_experience': { 'zh': '工作年限', 'en': 'Years of Experience' },
    'summary': { 'zh': '个人总结', 'en': 'Summary' },
    'countries': { 'zh': '国家', 'en': 'Countries' },
    'interests': { 'zh': '兴趣爱好', 'en': 'Interests' },
    'industry2': { 'zh': '子行业', 'en': 'Secondary Industry' },
    'linkedin_user_name': { 'zh': '领英用户名', 'en': 'LinkedIn Username' },
    
    // Twitter数据
    'twitter_id': { 'zh': 'Twitter ID', 'en': 'Twitter ID' },
    'name': { 'zh': '用户姓名', 'en': 'User Name' },
    'screen_name': { 'zh': '用户屏幕名称', 'en': 'Screen Name' },
    'url': { 'zh': '个人网址', 'en': 'Personal URL' },
    'description': { 'zh': '用户的描述信息', 'en': 'User Description' },
    'protected': { 'zh': '是否受保护', 'en': 'Protected' },
    'verified': { 'zh': '是否经过验证', 'en': 'Verified' },
    'followers_count': { 'zh': '关注者数量', 'en': 'Followers Count' },
    'friends_count': { 'zh': '好友数量', 'en': 'Friends Count' },
    'listed_count': { 'zh': '被列入列表的数量', 'en': 'Listed Count' },
    'favourites_count': { 'zh': '喜欢的推文数量', 'en': 'Favorites Count' },
    'statuses_count': { 'zh': '发布的推文数量', 'en': 'Statuses Count' },
    'default_profile': { 'zh': '是否使用默认个人资料', 'en': 'Default Profile' },
    'default_profile_image': { 'zh': '是否使用默认个人资料图片', 'en': 'Default Profile Image' },
    'last_status_created_at': { 'zh': '最后一条推文的创建时间', 'en': 'Last Status Created At' },
    'last_status_source': { 'zh': '最后一条推文的来源', 'en': 'Last Status Source' },
    'created_at': { 'zh': '用户账户的创建时间', 'en': 'Account Created At' }
  };
  
  // 先尝试用小写key匹配
  if (fieldLabels[keyLower]) {
    return isEnglish ? fieldLabels[keyLower].en : fieldLabels[keyLower].zh;
  }
  
  // 尝试用原始key匹配
  if (fieldLabels[key]) {
    return isEnglish ? fieldLabels[key].en : fieldLabels[key].zh;
  }
  
  // 如果仍未找到匹配，返回原始key并进行格式化
  if (isEnglish) {
    // 英文环境下的格式化处理
    if (key.includes('_')) {
      // 下划线格式转为空格分隔，并将首字母大写
      return key.split('_')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join(' ');
    } else if (/[A-Z]/.test(key)) {
      // 驼峰格式转为空格分隔，并将首字母大写
      return key.replace(/([A-Z])/g, ' $1')
        .trim()
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
        .join(' ');
    }
    return key.charAt(0).toUpperCase() + key.slice(1); // 首字母大写
  }
  
  // 中文环境下，如果没有映射就返回原始字段名
  return key;
};

// 批量反查相关方法
// 文件选择变化
const handleFileChange = (file, fileListParam) => {
  selectedFile.value = file.raw;
  fileList.value = fileListParam;
};

// 文件超出限制
const handleExceed = () => {
  if (getCurrentLanguage() === 'zh') {
    ElMessage.warning('只能上传一个文件，请先移除已选文件');
  } else {
    ElMessage.warning('Only one file can be uploaded, please remove the selected file first');
  }
};

// 取消批量上传
const cancelBatchUpload = () => {
  if (batchUploading.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('反查正在进行中，请稍后再试');
    } else {
      ElMessage.warning('Reverse check is in progress, please try again later');
    }
    return;
  }
  
  showBatchDialog.value = false;
  selectedFile.value = null;
  fileList.value = [];
  uploadProgress.value = 0;
  uploadStatus.value = '';
  uploadStatusText.value = '';
};

// 提交批量反查
const submitBatchReverse = async () => {
  if (!selectedFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先选择要上传的Excel文件');
    } else {
      ElMessage.warning('Please select an Excel file to upload first');
    }
    return;
  }

  // 检查文件格式
  const fileName = selectedFile.value.name;
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件格式不正确，只支持.xlsx和.xls格式');
    } else {
      ElMessage.error('Invalid file format, only .xlsx and .xls are supported');
    }
    return;
  }

  // 检查token
  const token = localStorage.getItem('token');
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录');
    } else {
      ElMessage.warning('You are not logged in, please log in first');
    }
    router.push('/login');
    return;
  }

  // 准备FormData
  const formData = new FormData();
  formData.append('file', selectedFile.value);

  batchUploading.value = true;
  uploadProgress.value = 0;
  uploadStatus.value = '';
  
  if (getCurrentLanguage() === 'zh') {
    uploadStatusText.value = '正在上传文件...';
  } else {
    uploadStatusText.value = 'Uploading file...';
  }

  try {
    const response = await axios.post('/api/social-media-lookup/batch', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob', // 重要：接收二进制数据
      timeout: 900000, // 15分钟超时（批量反查数据量大时需要更长时间）
      onUploadProgress: (progressEvent) => {
        // 上传进度
        if (progressEvent.total) {
          uploadProgress.value = Math.round((progressEvent.loaded * 50) / progressEvent.total);
        }
      },
      onDownloadProgress: (progressEvent) => {
        // 下载进度
        if (progressEvent.total) {
          const downloadProgress = Math.round((progressEvent.loaded * 50) / progressEvent.total);
          uploadProgress.value = 50 + downloadProgress;
        } else {
          uploadProgress.value = 75;
        }
        
        if (getCurrentLanguage() === 'zh') {
          uploadStatusText.value = '正在处理反查结果...';
        } else {
          uploadStatusText.value = 'Processing reverse check results...';
        }
      }
    });

    // 检查响应是否为错误JSON（而非Excel文件）
    if (response.data.type === 'application/json') {
      // 说明返回的是错误信息
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const errorData = JSON.parse(e.target.result);
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(errorData.message || '批量反查失败');
          } else {
            ElMessage.error(errorData.message || 'Batch reverse check failed');
          }
        } catch (parseError) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('服务器返回了未知错误');
          } else {
            ElMessage.error('Server returned an unknown error');
          }
        }
      };
      reader.readAsText(response.data);
      
      uploadProgress.value = 0;
      uploadStatus.value = 'exception';
      if (getCurrentLanguage() === 'zh') {
        uploadStatusText.value = '反查失败';
      } else {
        uploadStatusText.value = 'Reverse check failed';
      }
      return;
    }

    // 成功接收到Excel文件，触发下载
    uploadProgress.value = 100;
    uploadStatus.value = 'success';
    if (getCurrentLanguage() === 'zh') {
      uploadStatusText.value = '反查完成，正在下载...';
    } else {
      uploadStatusText.value = 'Reverse check completed, downloading...';
    }
    
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition'];
    let filename = `批量社媒反查结果_${new Date().getTime()}.xlsx`;
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      }
    }
    
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('批量反查完成，结果已下载');
    } else {
      ElMessage.success('Batch reverse check completed, results downloaded');
    }
    
    // 重置状态
    setTimeout(() => {
      showBatchDialog.value = false;
      selectedFile.value = null;
      fileList.value = [];
      uploadProgress.value = 0;
      uploadStatus.value = '';
      uploadStatusText.value = '';
    }, 1500);

  } catch (error) {
    console.error('批量反查错误:', error);
    
    uploadProgress.value = 0;
    uploadStatus.value = 'exception';
    
    if (error.response) {
      // 服务器返回了错误
      if (error.response.status === 400) {
        // 尝试解析错误消息
        try {
          const errorBlob = error.response.data;
          const reader = new FileReader();
          reader.onload = (e) => {
            try {
              const errorData = JSON.parse(e.target.result);
              const errorMsg = errorData.msg || errorData.message || '批量反查失败';
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error(errorMsg);
                uploadStatusText.value = errorMsg;
              } else {
                ElMessage.error(errorData.msg || errorData.message || 'Batch reverse check failed');
                uploadStatusText.value = errorData.msg || errorData.message || 'Reverse check failed';
              }
            } catch (parseError) {
              if (getCurrentLanguage() === 'zh') {
                ElMessage.error('批量反查失败，请检查文件格式');
                uploadStatusText.value = '反查失败';
              } else {
                ElMessage.error('Batch reverse check failed, please check file format');
                uploadStatusText.value = 'Reverse check failed';
              }
            }
          };
          reader.readAsText(errorBlob);
        } catch (e) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('批量反查失败，请检查文件格式');
            uploadStatusText.value = '反查失败';
          } else {
            ElMessage.error('Batch reverse check failed, please check file format');
            uploadStatusText.value = 'Reverse check failed';
          }
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`服务器错误 (${error.response.status})`);
          uploadStatusText.value = `服务器错误 (${error.response.status})`;
        } else {
          ElMessage.error(`Server error (${error.response.status})`);
          uploadStatusText.value = `Server error (${error.response.status})`;
        }
      }
    } else if (error.request) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器未响应，请检查网络连接');
        uploadStatusText.value = '服务器未响应';
      } else {
        ElMessage.error('No response from server, please check network');
        uploadStatusText.value = 'No server response';
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('请求失败: ' + error.message);
        uploadStatusText.value = '请求失败';
      } else {
        ElMessage.error('Request failed: ' + error.message);
        uploadStatusText.value = 'Request failed';
      }
    }
  } finally {
    batchUploading.value = false;
  }
};

// 下载模板
const downloadTemplate = async (type) => {
  const lang = getCurrentLanguage();
  const token = localStorage.getItem('token');
  
  try {
    const response = await axios.get('/api/social-media-lookup/batch/template', {
      params: { lang: lang, type: type },
      headers: {
        'Authorization': `Bearer ${token}`
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    let fileName;
    if (lang === 'zh') {
      fileName = type === 'twitter' ? '社媒反查_twitter模板.xls' : '社媒反查_linkedIn模板.xls';
    } else {
      fileName = type === 'twitter' ? 'social_media_twitter_Template.xls' : 'social_media_linkedIn_Template.xls';
    }
    
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    if (lang === 'zh') {
      ElMessage.success('模板下载成功');
    } else {
      ElMessage.success('Template downloaded successfully');
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    if (lang === 'zh') {
      ElMessage.error('模板下载失败，请稍后重试');
    } else {
      ElMessage.error('Template download failed, please try again later');
    }
  }
};
</script>

<style scoped>
.social-media-reverse-check-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.search-content {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 20px;
}

.description {
  color: #606266;
  font-size: 14px;
  max-width: 800px;
  margin: 0 auto;
}

.search-actions {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  margin: 0 5px;
  padding: 10px 20px;
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  width: 100%;
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
}

.search-input {
  flex: 1;
}

.search-button {
  width: 80px;
  margin-left: 10px;
}

.api-error-alert {
  margin-bottom: 20px;
}

.feature-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
}

.feature-card {
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.feature-card .icon {
  margin-right: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.blue-icon {
  color: #409eff;
  background-color: #ecf5ff;
  padding: 10px;
  border-radius: 10px;
}

.green-icon {
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 10px;
  border-radius: 10px;
}

.purple-icon {
  color: #9361ff;
  background-color: #f9f0ff;
  padding: 10px;
  border-radius: 10px;
}

.orange-icon {
  color: #ff9a00;
  background-color: #fff7e6;
  padding: 10px;
  border-radius: 10px;
}

.card-content {
  flex: 1;
}

.card-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
}

.card-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 搜索结果样式 */
.search-results {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.results-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.result-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.result-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.result-source {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  background-color: #f0f2f5;
  color: #606266;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  min-width: 100px;
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
  word-break: break-all;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.copy-btn {
  margin-left: 10px;
  padding: 4px 8px;
  font-size: 12px;
}

.load-more {
  margin-top: 20px;
  text-align: center;
}

.no-results {
  margin-top: 40px;
  text-align: center;
}

.loading-container {
  margin-top: 20px;
  padding: 20px;
}

/* 批量反查按钮样式 */
.batch-search-btn {
  margin-left: 10px;
}

/* 批量反查对话框样式 */
.batch-dialog-content {
  padding: 10px 0;
}

.batch-dialog-content p {
  margin: 8px 0;
  line-height: 1.6;
  font-size: 14px;
}

/* 上传组件样式优化 */
:deep(.el-upload-dragger) {
  padding: 40px 20px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style> 
